var args = arguments[0] || {};
var ViewNavigator = require('utils/ViewNavigator');
var fb = Alloy.Globals.Facebook;

var SockJS = require('utils/sockjs-tt');
var Stomp = require('utils/stomp');

var IMG_STATUS_WAITING = "/images/status_waiting.png";
var IMG_STATUS_REJECTED = "/images/status_rejected.png";
var IMG_STATUS_ACCEPTED = "/images/status_accepted.png";

var listInvited = [];
var listFriends = [];
var status = "accepted";
var me = null;
var SelfieView = function(args) {
	
	Ti.App.addEventListener("new_invited", updateInvitationList);
	
	$.usieId.text = args.id;
	me = args.me;
	Ti.App.addEventListener('invite', function(e) {
		addInvitedFriends(e);
	});

	Ti.App.addEventListener('refresh_status', function(e) {

		if (status) {
			listFriends[4].status = {
				image : IMG_STATUS_ACCEPTED
			};
			listFriends[2].status = {
				image : IMG_STATUS_ACCEPTED
			};
			listFriends[1].status = {
				image : IMG_STATUS_ACCEPTED
			};
		} else
			listFriends[0].status = {
				image : IMG_STATUS_REJECTED
			};
		listFriends[3].status = {
			image : IMG_STATUS_REJECTED
		};

		$.invitedList.setItems(listFriends);
	});

	Ti.App.addEventListener("user_accepted", function(e) {
		//alert("SelfieView" + JSON.stringify(e.aux));
	});
};

function updateInvitationList(e) {
	var invitedUsers = [];
	for (var i = 0, users = e.aux.listInvited; i < users.length; i++) {
		//if (me.id !== users[i].externalId) {
			alert(JSON.stringify(users));
			//$.invitedList.setItems([ users[i] ]);
		//}
	}
}

$.addContact.addEventListener("click", function() {
	ViewNavigator.navigateToView("Search", {
		usie : args,
		listFriends : listFriends
	});
});

$.takePicture.addEventListener("click", function() {
	ViewNavigator.navigateToView("TakePicture");
});

function addInvitedFriends(e) {
	var newFriends = [];
	for (var i = 0; i < e.listInvited.length; i++) {
		var friend = {
			id : e.listInvited[i].id,
			name : {
				text : e.listInvited[i].name
			},
			picture : {
				image : e.listInvited[i].picture.data.url
			},
			check : {
				image : IMG_STATUS_WAITING
			},
			target : e.listInvited[i]
		};
		newFriends.push(friend);
		listFriends.push(friend);
	}
	$.invitedList.appendItems(newFriends);

}

// function subscribe() {
	// var WS_URL = Alloy.CFG.wsUrl,
		// socket = new SockJS(WS_URL),
		// client = Stomp.over(socket);
	// var acceptedUsers = [];
// 
	// client.connect({}, function() {
		// this.subscribe("/topic/invitation", function(message) {
			// var aux = JSON.parse(message.body);
			// Ti.App.fireEvent("new_invited", {
				// aux : aux
			// });
		// });
	// });
// }

$.view = new SelfieView(args);
